package br.ufrgs.dbproject;

import java.security.InvalidParameterException;

import br.ufrgs.dbproject.exceptions.DataNotFoundException;
import br.ufrgs.dbproject.pathcache.Cache;
import br.ufrgs.dbproject.pathcache.CacheEntry;
import br.ufrgs.dbproject.pathcache.Path;

public class PathBuilder {

	private final Cache cache;

	private Path lastCreatedPath;

	private CacheEntry lastCachedEntry;
	
	private Integer sequenceID;

	public PathBuilder(Cache cache, Path rootPath) {
		
		this.cache = cache;
		this.lastCreatedPath = rootPath;
		
		this.sequenceID = 0;
	}

	public PathBuilder() {
		this(new Cache(), Path.createEmptyPath());
	}

	public CacheEntry append(String node) {
		
		if (node == null || node.isEmpty()) {
			throw new InvalidParameterException("node cannot be null or empty!");
		}
		
		Path newPath = lastCreatedPath.concat(node);
		lastCreatedPath = newPath;

		try {
			return cache.fetchEntry(lastCreatedPath);
			
		} catch (DataNotFoundException e) {
			
			CacheEntry entry = cache.put(++sequenceID, lastCreatedPath);
			lastCachedEntry = entry;
			return entry;
		}
 	}

	public void removeTail() {
		this.lastCreatedPath = lastCreatedPath.removeTail();
	}

	public Path getLastCreatedPath() {
		return lastCreatedPath;
	}

	public CacheEntry getLastCachedEntry() {
		return lastCachedEntry;
	}
}
